import tensorflow as tf
import numpy as np


# 添加层函数
def add_layer(inputs, in_size, out_size, activation_function=None):
    # 权重矩阵
    Weights = tf.Variable(tf.random_normal([in_size, out_size]))
    biases = tf.Variable(tf.zeros([1, out_size]) + 0.1)
    Wx_plus_b = tf.matmul(tf.cast(inputs, tf.float32), Weights) + biases
    if activation_function == None:
        outputs = Wx_plus_b
    else:
        outputs = activation_function(Wx_plus_b)
    return outputs


# linspace 从-1到1之间300个数的等差数列
# newaxis 增加一个维
# 开始 x_data 为一行300列，作用后为300行1列
x_data = np.linspace(-1, 1, 300)[:, np.newaxis]
# normal 标准正态分布 miu=0 sigma=0.05
noise = np.random.normal(0, 0.05, x_data.shape)
y_data = np.square(x_data) - 0.5 + noise

xs = tf.placeholder(tf.float32, [None, 1])
ys = tf.placeholder(tf.float32, [None, 1])
# l1层
l1 = add_layer(x_data, 1, 10, activation_function=tf.nn.relu)
# 输出层
prediction = add_layer(l1, 10, 1, activation_function=None)
# 误差函数
loss = tf.reduce_mean(tf.reduce_sum(tf.square(y_data - prediction), reduction_indices=[1]))
# 训练
train_step = tf.train.GradientDescentOptimizer(0.1).minimize(loss)
# 初始化所有变量
init = tf.global_variables_initializer()
sess = tf.Session()
sess.run(init)

for i in range(1000):
    sess.run(train_step, feed_dict={xs:x_data, ys:y_data})

    if i % 50 == 0:
        print(sess.run(loss, feed_dict={xs:x_data, ys:y_data}))
